package com.example.himalaya;

import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.*;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import com.example.himalaya.adapters.PlayerTrackViewPagerAdapter;
import com.example.himalaya.interfaces.IPlayerViewCallback;
import com.example.himalaya.presenters.PlayerPresenter;
import com.example.himalaya.utils.ImageBlur;
import com.example.himalaya.utils.LogUtil;
import com.example.himalaya.views.PlayListPopupWindow;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PlayerActivity extends AppCompatActivity implements IPlayerViewCallback {
    private static final String TAG = "PlayerActivity";
    private ImageView mControlPlayOrPauseBtn;
    private PlayerPresenter mPlayerPresenter;

    private SimpleDateFormat mMinFormat = new SimpleDateFormat("mm:ss");
    private SimpleDateFormat mHourFormat = new SimpleDateFormat("hh:mm:ss");
    private TextView mTrackTotalDurationTv;
    private TextView mCurrentPositionTv;
    private SeekBar mTrackSeekBar;

    private int mCurrentProgress = 0;//当前进度条进度
    private boolean mIsUserTouchProgress = false;//用户是否触摸进度条
    private ImageView mPlayPreBtn;
    private ImageView mPlayNextBtn;
    private TextView mTrackTitleTv;
    private ViewPager mTrackViewPager;
    private PlayerTrackViewPagerAdapter mPlayerTrackViewPagerAdapter;

    private boolean mIsUserTouchPage = false;
    private ImageView mPlayerModeSwitchBtn;

    private static Map<XmPlayListControl.PlayMode, XmPlayListControl.PlayMode> sPlayModeRule = new HashMap<>();
    private XmPlayListControl.PlayMode mCurrentMode = PLAY_MODEL_LIST_LOOP;
    //设置播放器模式，mode取值为PlayMode中的下列之一
    //PLAY_MODEL_LIST列表播放
    //PLAY_MODEL_LIST_LOOP列表循环 ,默认模式
    //PLAY_MODEL_RANDOM 随机播放
    //PLAY_MODEL_SINGLE单曲播放
    //PLAY_MODEL_SINGLE_LOOP 单曲循环播放
    static {
        sPlayModeRule.put(PLAY_MODEL_LIST_LOOP, PLAY_MODEL_RANDOM);
        sPlayModeRule.put(PLAY_MODEL_RANDOM, PLAY_MODEL_SINGLE_LOOP);
        sPlayModeRule.put(PLAY_MODEL_SINGLE_LOOP, PLAY_MODEL_LIST_LOOP);
    }

    private ImageView mPlayerListBtn;
    private PlayListPopupWindow mPlayListPopupWindow;
    private ValueAnimator mEnterBgAnimator;
    private ValueAnimator mOutBgAnimator;

    private boolean mCurrentPlayListIsOrder = true;
    private ImageView mPlayPageBgIv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        //设置顶部状态栏为透明颜色
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        //隐藏状态栏，布局充满整个屏幕，状态icon图标在原状态栏位置现布局顶部显示
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

        initView();
        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mPlayerPresenter.registerViewCallBack(this);
        initBgAnimation();
        initEvent();
        updatePlayState(mPlayerPresenter.isPlaying());
        updateProgress(mPlayerPresenter.getCurrentProgressPos(), mPlayerPresenter.getProgressDuraton());
    }

    private void updatePlayState(boolean playing) {
        if (playing) {
            mControlPlayOrPauseBtn.setImageResource(R.drawable.selector_player_pause);
        } else {
            mControlPlayOrPauseBtn.setImageResource(R.drawable.selector_player_play);
        }
    }

    private void updateProgress(int currentProgressPos, int progressDuraton) {
        mTrackSeekBar.setMax(progressDuraton);
        String totalDurationText;
        String currentPositionText;
        if (progressDuraton > 1000 * 60 * 60) {
            totalDurationText = mHourFormat.format(progressDuraton);
            currentPositionText = mHourFormat.format(currentProgressPos);
        } else {
            totalDurationText = mMinFormat.format(progressDuraton);
            currentPositionText = mMinFormat.format(currentProgressPos);
        }
        //更新总时长
        if (mTrackTotalDurationTv != null) {
            mTrackTotalDurationTv.setText(totalDurationText);
        }
        //更新当前时间
        if (mCurrentPositionTv != null) {
            mCurrentPositionTv.setText(currentPositionText);
        }
        //更新进度条
        if (!mIsUserTouchProgress) {
            mTrackSeekBar.setProgress(currentProgressPos);
        }
    }


    private void initView() {
        mControlPlayOrPauseBtn = findViewById(R.id.play_or_pause_btn);
        mTrackTotalDurationTv = findViewById(R.id.track_duration);
        mCurrentPositionTv = findViewById(R.id.current_position);
        mTrackSeekBar = findViewById(R.id.track_seek_bar);
        mPlayPreBtn = findViewById(R.id.play_pre_btn);
        mPlayNextBtn = findViewById(R.id.play_next_btn);
        mTrackTitleTv = findViewById(R.id.player_track_title);
        mTrackViewPager = findViewById(R.id.track_view_pager);
        mPlayerTrackViewPagerAdapter = new PlayerTrackViewPagerAdapter();
        mTrackViewPager.setAdapter(mPlayerTrackViewPagerAdapter);
        mPlayerModeSwitchBtn = findViewById(R.id.player_mode_switch_btn);
        mPlayerListBtn = findViewById(R.id.player_list_btn);
        mPlayListPopupWindow = new PlayListPopupWindow();
        mPlayPageBgIv = findViewById(R.id.play_page_bg_iv);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        mControlPlayOrPauseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果现在的状态是正在播放的，那么就暂停
                if (mPlayerPresenter.isPlaying()) {
                    mPlayerPresenter.pause();
                } else {
                    //如果现在的状态是非播放的，那么就让播放器播放节目
                    mPlayerPresenter.play();
                }

            }
        });
        mTrackSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mCurrentProgress = progress;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mIsUserTouchProgress = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mIsUserTouchProgress = false;
                //手离开拖动进度条的时候更新进度
                mPlayerPresenter.seekTo(mCurrentProgress);
            }
        });
        mPlayPreBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playPre();
                }
            }
        });
        mPlayNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playNext();
                }
            }
        });

        mTrackViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (mPlayerPresenter != null&&mIsUserTouchPage) {
                    mPlayerPresenter.playByListItemIndex(position);
                    LogUtil.d(TAG,"pos -->"+position);
                }
                mIsUserTouchPage = false;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mTrackViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        mIsUserTouchPage = true;
                    break;


                }
                return false;
            }
        });
        mPlayerModeSwitchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchPlayMode();
            }
        });
        mPlayerListBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //展示播放列表
                mPlayListPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

                //修改背景的透明有一个渐变的过程
                mEnterBgAnimator.start();

            }
        });
        mPlayListPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //pop窗体消失以后，恢复透明度
                mOutBgAnimator.start();
            }
        });
        mPlayListPopupWindow.setPlayListItemClickListener(new PlayListPopupWindow.PlayListItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playByListItemIndex(position);
                }
            }
        });

        mPlayListPopupWindow.setPlayListActionListener(new PlayListPopupWindow.PlayListActionListener() {
            @Override
            public void onPlayModeCLick() {
                //点击了播放模式
                switchPlayMode();
            }

            @Override
            public void onOrderClick() {
                //点击了列表排序
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.reversePlayListOrder();
                }
            }
        });
    }

    private void switchPlayMode() {
        //根据当前的mode获取下一个mode
        XmPlayListControl.PlayMode playMode = sPlayModeRule.get(mCurrentMode);
        //修改播放模式
        if (mPlayerPresenter != null) {
            mPlayerPresenter.switchPlayMode(playMode);
        }
    }

    private void initBgAnimation() {
        mEnterBgAnimator = ValueAnimator.ofFloat(1.0f, 0.5f);
        mEnterBgAnimator.setDuration(500);
        mEnterBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                //处理背景，有点透明度
                updateBgAlpha(value);
            }
        });

        mOutBgAnimator = ValueAnimator.ofFloat(0.5f, 1.0f);
        mOutBgAnimator.setDuration(500);
        mOutBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                updateBgAlpha(value);
            }
        });
    }

    /**
     * 更新背景透明度
     * @param alpha 透明度，数字越小透明度越低越黑
     */
    public void updateBgAlpha(float alpha) {
        Window window = getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.alpha = alpha;
        window.setAttributes(attributes);
    }



    @Override
    public void onPlayStart() {
        //开始播放，修改UI成暂停的按钮
        mControlPlayOrPauseBtn.setImageResource(R.drawable.selector_player_pause);
    }

    @Override
    public void onPlayPause() {
        //暂停播放，修改UI成播放的按钮
        mControlPlayOrPauseBtn.setImageResource(R.drawable.selector_player_play);
    }

    @Override
    public void onPlayStop() {
        mControlPlayOrPauseBtn.setImageResource(R.drawable.selector_player_play);
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onNextPlay(Track track) {

    }

    @Override
    public void onTrackListUI(List<Track> tracks) {
        if (tracks != null&&tracks.size()>0) {
            //把数据设置到适配器里
            if (mPlayerTrackViewPagerAdapter != null) {
                mPlayerTrackViewPagerAdapter.setTrackListData(tracks);
            }


            //数据回来后，也要给节目列表一份
            if (mPlayListPopupWindow != null) {
                mPlayListPopupWindow.setPlayListData(tracks);
            }
        }
    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode currentMode) {
        //更新当前的播放模式
        mCurrentMode = currentMode;
        //更新popWindows里的播放模式UI
        mPlayListPopupWindow.updatePlayMode(mCurrentMode);
        //更新播放器播放模式按钮图片
        updatePlayModeBtnImg();
    }

    private void updatePlayModeBtnImg() {
        int resId = R.drawable.selector_player_mode_loop;
        switch (mCurrentMode) {
            case PLAY_MODEL_LIST_LOOP:
                resId=R.drawable.selector_player_mode_loop2;
                break;
            case PLAY_MODEL_RANDOM:
                resId=R.drawable.selector_player_mode_loop_random2;
                break;
            case PLAY_MODEL_SINGLE_LOOP:
                resId=R.drawable.selector_player_mode_loop_one2;
                break;
        }
        mPlayerModeSwitchBtn.setImageResource(resId);
    }

    @Override
    public void onProgressChange(int currentProgress, int totalDuration) {
        updateProgress(currentProgress, totalDuration);
    }

    @Override
    public void onAdLoading() {
        Toast.makeText(this,"请稍等,正在播放广告...",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onTrackUpdateUI(Track track,int index) {


        if (track != null) {
            //更新标题
            if (mTrackTitleTv != null) {
                mTrackTitleTv.setText(track.getTrackTitle());
            }
            //更新图片
            if (mTrackViewPager != null) {
                mTrackViewPager.setCurrentItem(index,true);
            }
            //更新popWindows播放列表UI
            if (mPlayListPopupWindow != null) {
                mPlayListPopupWindow.setCurrentPlayPosition(index);
            }

            String coverUrlLarge = track.getCoverUrlLarge();
            if (!TextUtils.isEmpty(coverUrlLarge)) {
                Picasso.with(this).load(coverUrlLarge).into(mPlayPageBgIv, new Callback() {
                    @Override
                    public void onSuccess() {
                        //Picasso方式获取图片是异步的，所以要在成功后，并且不等于空的情况下设置模糊效果
                        Drawable drawable = mPlayPageBgIv.getDrawable();
                        if (drawable != null) {
                            //图片设置高斯模糊效果
                            ImageBlur.makeBlur(mPlayPageBgIv, PlayerActivity.this);
                        }
                    }

                    @Override
                    public void onError() {
                        LogUtil.d(TAG, "Picasso框架方式载入图片失败");
                    }
                });

            } else {
                Picasso.with(this).load(R.drawable.play_page_default_bg).into(mPlayPageBgIv, new Callback() {
                    @Override
                    public void onSuccess() {
                        //Picasso方式获取图片是异步的，所以要在成功后，并且不等于空的情况下设置模糊效果
                        Drawable drawable = mPlayPageBgIv.getDrawable();
                        if (drawable != null) {
                            //图片设置高斯模糊效果
                            ImageBlur.makeBlur(mPlayPageBgIv, PlayerActivity.this);
                        }
                    }

                    @Override
                    public void onError() {
                        LogUtil.d(TAG, "Picasso框架方式载入图片失败");
                    }
                });

            }
        }
    }

    @Override
    public void onUpdatePlayListOrder(boolean isReverse) {
        mPlayListPopupWindow.updatePlayListOrder(isReverse);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unRegisterViewCallBack(this);
            mPlayerPresenter = null;
        }
    }
}